package com.lmf.juc.ReadWriteLock;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 演示写锁降级为读锁：（获取了写锁后，可以再次获取读锁。）
 *      方法流程：获取写锁 -> 获取读锁（降级写锁） -> 释放写锁 -> 释放读锁
 *      注意：读锁不能升级为写锁（即，获取了读锁，就不能再获取写锁，必须等读锁代码执行结束了，才可以去执行写锁代码）
 */
public class ReadWriteLockDemo2 {
    public static void main(String[] args) {
        //创建可重入读写锁
        ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
        ReentrantReadWriteLock.ReadLock readLock = rwLock.readLock();//读锁
        ReentrantReadWriteLock.WriteLock writeLock = rwLock.writeLock();//写锁

        //获取写锁
        writeLock.lock();
        System.out.println("获取写锁");

        //获取读锁
        readLock.lock();
        System.out.println("获取读锁");

        //释放写锁
        writeLock.unlock();
        System.out.println("释放写锁");

        //释放读锁
        readLock.unlock();
        System.out.println("释放读锁");
    }
}
